<template>
  <el-dialog :title="dialogTitle" v-model="isVisble" width="30%">
    <el-form ref="formRef" :rules="rules" :model="form">
      <el-form-item label="账号" v-if="!isConfirm" label-width="80px">
        <el-input v-model="acc" disabled></el-input>
      </el-form-item>
      <el-form-item label="输入密码" label-width="80px" prop="password">
        <el-input
          :type="passwordType"
          v-model="form.password"
          placeholder="请输入8～16位,含字母、数字、符号的密码"
        >
          <template #suffix>
            <i
              class="el-input__icon"
              :class="{ 'el-icon-unlock': isOpen, 'el-icon-lock': !isOpen }"
              @click="openChange"
            ></i>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        v-if="isConfirm"
        label="确认密码"
        label-width="80px"
        prop="confirm"
      >
        <el-input
          :type="passwordType"
          v-model="form.confirm"
          placeholder="请输入确认密码"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="isVisble = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script>
  import { reactive, ref, computed, nextTick } from 'vue'
  import { ElLoading } from 'element-plus'
  import { editPW, bindAcc } from '@/api/modules/orgPerson.js'
  import md5 from 'md5'
  import { ElMessage } from 'element-plus'
  import common from '@/utils/common'
  export default {
    name: 'EditPassword',
    // 不填就是修改密码，type=1 就是验证绑定账号验证过程
    props: { modelValue: Boolean, userId: Number, account: String },
    emits: ['close', 'success', 'update:modelValue'],
    setup(props, context) {
      let isVisble = computed({
        get() {
          return props.modelValue
        },
        set(val) {
          context.emit('update:modelValue', val)
        },
      })
      // 界面初始化
      const isConfirm = computed(() => {
        if (props.account) {
          return false
        }
        return true
      })
      const dialogTitle = computed(() => {
        if (props.account) {
          return '请输入您绑定的账号密码'
        }
        return '修改密码'
      })
      // 显示的账号
      // console.log('props.account =' + props.account)
      // let acc = ref(props.value)
      // console.log('acc =' + JSON.stringify(acc))
      const acc = computed(() => {
        return props.account
      })
      // icon相关
      let isOpen = ref(false)
      let passwordType = ref('password')
      const openChange = function () {
        console.log('openChange')
        isOpen.value = !isOpen.value
        passwordType.value = isOpen.value ? '' : 'password'
      }
      // 表单相关
      const form = reactive({ password: null, confirm: null })
      const validF = function (rules, value, cb) {
        if (form.password !== form.confirm) {
          cb(new Error('两次密码要输入一样'))
        }
        cb()
      }
      const checkPasswordF = function (rules, value, cb) {
        if (!common.checkPassword(form.password)) {
          cb(new Error('请输入8～16位,含字母、数字、符号的密码'))
        }
        cb()
      }
      const formRef = ref(null)
      const rules = {
        password: [
          {
            required: true,
            min: 8,
            max: 16,
            message: '请输入8～16位,含字母、数字、符号的密码',
            trigger: 'blur',
          },
          {
            required: true,
            validator: checkPasswordF,
            message: '请输入8～16位,含字母、数字、符号的密码',
            trigger: 'blur',
          },
        ],
        confirm: [
          {
            required: true,
            validator: validF,
            message: '两次密码要输入一样',
            trigger: 'blur',
          },
        ],
      }
      const toEditPW = async function (id, pw) {
        const loading = ElLoading.service()
        editPW({ id, password: md5(pw) })
          .then(() => {
            loading.close()
            successF('密码修改成功')
          })
          .catch(() => {
            loading.close()
          })
      }
      const toBindAcc = function (account, pw) {
        const loading = ElLoading.service()
        bindAcc({ account, password: md5(pw) })
          .then((res) => {
            successF('账号验证成功', { userId: res.data.userId })
          })
          .catch(() => {
            loading.close()
          })
      }
      const successF = async function (message, obj) {
        const loading = ElLoading.service()
        await nextTick()
        loading.close()
        isVisble.value = false
        ElMessage.success(message)
        context.emit('update:modelValue', false)
        if (obj) context.emit('success', obj)
      }
      const onSubmit = function (val) {
        console.log('val =' + JSON.stringify(val))
        formRef.value.validate((valid) => {
          if (valid) {
            ElLoading.service({
              fullscreen: true,
              background: 'rgba(0, 0, 0, 0.8)',
            })
            if (props.account) {
              toBindAcc(props.account, form.password)
            } else {
              toEditPW(props.userId, form.password)
            }
          }
        })
      }

      return {
        form,
        rules,
        onSubmit,
        isVisble,
        openChange,
        isOpen,
        passwordType,
        formRef,
        isConfirm,
        dialogTitle,
        acc,
      }
    },
  }
</script>
